package cn.edu.gcu.ssl.goods.controller;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

@Controller
@RequestMapping(value="/goods/file")
public class FileController {


		@ResponseBody
		@RequestMapping(value="picture")
		public Map<String,Object> uploadPicture(@RequestParam("file") MultipartFile file ,HttpServletRequest request, HttpServletResponse response){
			Map<String,Object> result = new HashMap<String,Object>();
			Map<String,Object> resultMap = new HashMap<String,Object>();
			//pattern 正则表达式规范+matcher 匹配
			 Pattern pattern = Pattern.compile(".+(.JPEG|.jpeg|.JPG|.jpg|.GIF|.gif|.BMP|.bmp|.PNG|.png)$");
		     String fileName=file.getOriginalFilename();  
		     if(!pattern.matcher(fileName.toLowerCase()).find()){
				result.put("statusCode", "400");
				result.put("message", "Format Error");
				result.put("resultMap",null);
				return result;
		     }
		     
		     
		     String basePath=request.getSession().getServletContext().getRealPath("/"); 
		     
		     
		     //文件类型(后缀)  
		     String fileType=fileName.substring(fileName.lastIndexOf("."), fileName.length());  
		     //文件路径(相对路径，建议存入数据库)  
		     String newFileName=System.currentTimeMillis()+fileType;  
		     String filePath=new SimpleDateFormat("yy/MM/dd").format(new Date()).toString();  
		     // 文件磁盘路径  
		     String path=basePath+"\\res\\img\\"+filePath;  
		     //创建目录  
		     File newFile = new File(path);  
		     // 如果目录不存在，则创建目录  
		     if (!newFile.isDirectory())    
		         newFile.mkdirs();  
		     //创建目标文件  
		     File resultFile = new File(path+"\\"+newFileName);  
		     //写入磁盘  
		     try {
		    	file.transferTo(resultFile);
				resultMap.put("url",filePath+"/"+newFileName);
				result.put("statusCode","200");
				result.put("message", "Request Success");
				result.put("resultMap", resultMap);
		     } catch (Exception e) {
				e.printStackTrace();
				result.put("statusCode", "400");
				result.put("message", "Request Fail");
				result.put("resultMap",null);
			 }
		     return result;
		}
	}

	
	
	
	

	
